package com.maxima.attendance.daos;

import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.maxima.attendance.pojos.Project;
import com.maxima.attendance.utils.HibernateUtils;

public class ProjectDAO {
	Map<String, Object> map;

	public Project add(Project project) {
		Session session = HibernateUtils.getSession();
		session.beginTransaction();
		session.save(project);
		session.getTransaction().commit();
		session.close();
		return project;
	}

	@SuppressWarnings("unchecked")
	public List<Project> getAll() {
		Session session = HibernateUtils.getSession();
		session.beginTransaction();
		List<Project> projects = null;
		try {
			projects = (List<Project>) session.createQuery("select p from Project p order by p.projectName").list();
		}
		catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		session.close();
		return projects;
	}

	public Project get(Integer id) {
		Session session = HibernateUtils.getSession();
		session.beginTransaction();
		Project project = null;
		try {
			project = (Project) session.createQuery("select p from Project p where p.id=" + id).uniqueResult();
		}
		catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		session.close();
		return project;
	}

	public void update(Project newProject) {
		Session session = HibernateUtils.getSession();
		session.beginTransaction();
		Project existingProject = null;
		try {
			existingProject = (Project) session.createQuery("select p from Project p where p.id=" + newProject.getId()).uniqueResult();
			existingProject.setProjectName(newProject.getProjectName());
			existingProject.setAgreement(newProject.getAgreement());
		}
		catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		session.close();
	}
	
	public boolean checkIfAlreadyPresent(String agreement) {
		Session session = HibernateUtils.getSession();
		session.beginTransaction();
		Criteria criteria = session.createCriteria(Project.class);
		criteria.add(Restrictions.eq("agreement", agreement));
		Integer x = criteria.list().size();
		session.close();
		return x != 0;
	}
}
